package com.feihong.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.Map;

/**
 * Json工具类
 * @author Filter
 */
public class JsonObjectUtils {
    private static ObjectMapper objectMapper = new ObjectMapper();

    public static String getJsonByObject(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    /**
     * 集合转Json
     * @param list
     * @return
     * @throws JsonProcessingException
     */
    public static String getJsonByList(List list) throws JsonProcessingException {
        return getJsonByObject(list);
    }

    /**
     * Json转对象
     * @param json
     * @param clz
     * @return
     * @throws JsonProcessingException
     */
    public static Object getObjectByString(String json,Class clz) throws JsonProcessingException {
        return objectMapper.readValue(json,clz);
    }

    /**
     * Json转集合
     * @param json
     * @return
     * @throws JsonProcessingException
     */
    public static List getListByString(String json) throws JsonProcessingException {
        return objectMapper.readValue(json, new TypeReference<List>() {});
    }

    /**
     * Json转Map
     * @param json
     * @return
     * @throws JsonProcessingException
     */
    public static Map getMapByString(String json) throws JsonProcessingException {
        return objectMapper.readValue(json, new TypeReference<Map>() {});
    }
}
